from django.shortcuts import render, redirect, HttpResponse, reverse
from django import forms
# Create your views here.
from app01 import models
from django.http.response import JsonResponse
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator


# def zz(request):
#     models.Assets.objects.filter(pk=1).update(times='2019-11-15 02:03:03.000')
#     models.Assets.objects.filter(pk=2).update(times='2019-11-13 00:00:00.000')
#     models.Assets.objects.filter(pk=3).update(times='2019-11-11 01:03:03.000')
#     return HttpResponse('111')


def classes(request):
    cla = models.Classes.objects.all()

    return render(request, 'classes.html', {'cla': cla})


def user(request):
    u = models.User.objects.all()
    return render(request, 'user.html', {'u': u})


def assets(request):
    a = models.Assets.objects.all()
    return render(request, 'assets.html', {'a': a})


def dele(request, a, num):
    dit = {
        'assets': models.Assets,
        'user': models.User,
        'classes': models.Classes,
    }

    mod = dit.get(a)
    mod.objects.filter(pk=num).delete()

    return JsonResponse({'k': 'ok'})


def class_name(value):
    if models.Classes.objects.filter(name=value):
        raise ValidationError('实验室已存在')


def class_room(value):
    if models.Classes.objects.filter(room=value):
        raise ValidationError('房间已使用')


class RegForm(forms.Form):
    name = forms.CharField(label="实验室",
                           required=True,
                           validators=[class_name])
    storey = forms.CharField(label='楼层')
    room = forms.CharField(label='房间号',
                           required=True,
                           max_length=3,
                           validators=[class_room,
                                       RegexValidator(r'[0-9]{3}', '请输入正确的房间号')],
                           )
    u_name = forms.fields.ChoiceField(
        choices=models.User.objects.values_list('id', 'name'),
        label="负责人",
        required=True,
        widget=forms.widgets.Select(),
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['u_name'].choices = models.User.objects.values_list('id', 'name')


def classes_add(request):
    form_obj = RegForm()
    if request.method == 'POST':
        form_obj = RegForm(request.POST)
        if form_obj.is_valid():
            # print(form_obj.cleaned_data)
            # print(request.POST)
            name = form_obj.cleaned_data.get('name')
            storey = form_obj.cleaned_data.get('storey')
            room = form_obj.cleaned_data.get('room')
            u_name = form_obj.cleaned_data.get('u_name')
            obj = models.Classes.objects.create(name=name, storey=storey, room=room, person_id=u_name)
            obj.save()
            return redirect('/classes/')

    return render(request, 'classes_add.html', {'form_obj': form_obj})


def user_name(value):
    if models.User.objects.filter(username=value):
        raise ValidationError('用户名已存在')


class RegForm1(forms.Form):
    def clean(self):
        # 全局钩子
        # 通过校验   返回self.cleaned_data
        # 不通过校验   抛出异常  _>   __all__
        password = self.cleaned_data.get('password')
        re_password = self.cleaned_data.get('re_password')
        if password == re_password:
            return self.cleaned_data
        else:
            self.add_error('password', '两次密码不一致!!')
            raise ValidationError('两次密码不一致')

    username = forms.CharField(label="用户名",
                               required=True,
                               validators=[user_name])
    password = forms.CharField(label='密码', widget=forms.PasswordInput)
    re_password = forms.CharField(label='确认密码', widget=forms.PasswordInput)
    name = forms.CharField(label='姓名', required=True, validators=[])
    number = forms.CharField(label='手机号',
                             required=True,
                             validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式不正确')]
                             )


def user_add(request):
    form_obj1 = RegForm1()
    if request.method == 'POST':
        form_obj1 = RegForm1(request.POST)
        if form_obj1.is_valid():
            print(form_obj1.cleaned_data)
            print(request.POST)
            username = form_obj1.cleaned_data.get('username')
            password = form_obj1.cleaned_data.get('password')
            name = form_obj1.cleaned_data.get('name')
            number = form_obj1.cleaned_data.get('number')
            obj = models.User.objects.create(username=username, password=password, name=name, number=number)
            obj.save()
            return redirect('/user/')

    return render(request, 'user_add.html', {'form_obj1': form_obj1})


class RegForm2(forms.Form):
    name = forms.CharField(label="名称",
                           required=True, )
    des = forms.CharField(label="描述",
                          required=True, )
    ass_id = forms.CharField(label="材料编号",
                             required=True, )

    c_name = forms.MultipleChoiceField(
        choices=models.Classes.objects.values_list('id', 'name'),
        label="所属实验室",
        required=True,
        widget=forms.widgets.SelectMultiple,
    )

    peo = forms.fields.ChoiceField(
        choices=models.User.objects.values_list('id', 'name'),
        label="购买人",
        required=True,
        widget=forms.widgets.Select,
    )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['c_name'].choices = models.Classes.objects.values_list('id', 'name')


def assets_add(request):
    form_obj2 = RegForm2()

    if request.method == 'POST':
        form_obj2 = RegForm2(request.POST)
        if form_obj2.is_valid():
            print(form_obj2.cleaned_data)
            print(request.POST)
            name = form_obj2.cleaned_data.get('name')
            des = form_obj2.cleaned_data.get('des')
            ass_id = form_obj2.cleaned_data.get('ass_id')
            c_name = form_obj2.cleaned_data.get('c_name')
            peo = form_obj2.cleaned_data.get('peo')
            obj = models.Assets.objects.create(name=name, des=des, ass_id=ass_id, people_id=peo)
            obj.assets_class.set(c_name)
            obj.save()
            return redirect('/assets/')

    return render(request, 'assets_add.html', {'form_obj1': form_obj2})


def user_e(request, u_pk):
    ret = models.User.objects.get(pk=u_pk)
    if request.method == 'POST':
        username = request.POST.get('username')
        name = request.POST.get('name')
        number = request.POST.get('number')
        if models.User.objects.filter(username=username):
            return render(request, 'user_e.html', {'u': ret, 'k': '用户名已存在'})
        elif not name:
            return render(request, 'user_e.html', {'u': ret, 'k1': '不能为空'})
        elif not number:
            return render(request, 'user_e.html', {'u': ret, 'k2': '不能为空'})

        else:

            ret.username = username
            ret.name = name
            ret.number = number
            ret.save()
            return redirect('/user/')
    return render(request, 'user_e.html', {'u': ret})


def classes_e(request, c_pk):
    ret = models.Classes.objects.get(pk=c_pk)
    ret_user = models.User.objects.all()
    if request.method == 'POST':
        c_name = request.POST.get('c_name')
        storey = request.POST.get('storey')
        room = request.POST.get('room')
        ass_id = request.POST.get('ass_id')
        if models.Classes.objects.filter(name=c_name):
            return render(request, 'classes_e.html', {'ret': ret, 'ret_user': ret_user, 'k': '已存在'})
        elif not c_name:
            return render(request, 'classes_e.html', {'ret': ret, 'ret_user': ret_user, 'k': '不能为空'})
        elif not storey:
            return render(request, 'classes_e.html', {'ret': ret, 'ret_user': ret_user, 'k1': '不能为空'})
        elif models.Classes.objects.filter(room=room):
            return render(request, 'classes_e.html', {'ret': ret, 'ret_user': ret_user, 'k2': '已存在'})
        else:
            ret.name = c_name
            ret.storey = storey
            ret.room = room
            ret.person_id = ass_id
            ret.save()
            return redirect('/classes/')

    return render(request, 'classes_e.html', {'ret': ret, 'ret_user': ret_user})


def assets_e(request, a_pk):
    print(333)
    ret = models.Assets.objects.get(pk=a_pk)
    assets_class = models.Classes.objects.all()

    if request.method == 'POST':
        print(222)
        c_name = request.POST.get('c_name')
        ass_id = request.POST.get('ass_id')
        ass_cla = request.POST.getlist('ass_cla')
        if not c_name:
            return render(request, 'assets_e.html', {'ret': ret, 'assets_clas': assets_class, 'k1': '不能为空'})
        if not ass_id:
            return render(request, 'assets_e.html', {'ret': ret, 'assets_clas': assets_class, 'k2': '不能为空'})
        if models.Assets.objects.filter(ass_id=ass_id):
            return render(request, 'assets_e.html', {'ret': ret, 'assets_clas': assets_class, 'k2': '编号已存在'})
        if not ass_cla:
            return render(request, 'assets_e.html', {'ret': ret, 'assets_clas': assets_class, 'k3': '不能为空'})
        else:
            print(111)
            ret.name = c_name
            ret.ass_id = ass_id
            ret.save()
            ret.assets_class.set(ass_cla)
            return redirect('/assets/')

    return render(request, 'assets_e.html', {'ret': ret, 'assets_clas': assets_class})
